def determinant(matrix):
    """递归计算方阵的行列式"""
    n = len(matrix)

    # 基础情况：1x1 矩阵
    if n == 1:
        return matrix[0][0]

    # 基础情况：2x2 矩阵
    if n == 2:
        return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]

    det = 0
    for col in range(n):
        # 计算代数余子式
        minor = [row[:col] + row[col + 1:] for row in matrix[1:]]
        sign = (-1) ** col
        det += sign * matrix[0][col] * determinant(minor)
    return det


# 测试示例
if __name__ == "__main__":
    matrix_3x3 = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]
    ]
    print("3x3 矩阵行列式:", determinant(matrix_3x3))

    matrix_2x2 = [[1, 2], [3, 4]]
    print("2x2 矩阵行列式:", determinant(matrix_2x2))
